package com.xxl.job.executor.core.config;

import com.alibaba.fastjson.JSON;
import com.mongodb.*;
import com.xxl.job.core.biz.model.DbInfo;
import com.xxl.job.core.enums.DbinfoBelongEnum;
import com.xxl.job.core.util.ListUtils;
import com.xxl.job.executor.dao.DbInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.*;

/**
 * 共享云mongodb配置
 */
//@Configuration
//@ConfigurationProperties(prefix="spring.data.mongodb.shared")
public class SharedMongoConfig {
    @Value("${Spring.data.mongodb.shared.host}")
    protected String host;
    @Value("${Spring.data.mongodb.shared.port}")
    protected int port;
    @Value("${Spring.data.mongodb.shared.username}")
    protected String username;
    @Value("${Spring.data.mongodb.shared.password}")
    protected String password;
    @Value("${Spring.data.mongodb.shared.database}")
    protected String database;

    @Autowired(required = false)
    private DbInfoMapper dbInfoMapper;

    public MongoDbFactory mongoDbFactory() {
        Map<String, String> map = new HashMap<>();
        map.put("belong", DbinfoBelongEnum.SHARED_MONGODB.getKey());
        List<DbInfo> dbInfos = dbInfoMapper.query(map);
        System.out.println(JSON.toJSONString(dbInfos));
        if(ListUtils.isNotEmpty(dbInfos)) {
            DbInfo dbInfo = dbInfos.get(0);
            return new SimpleMongoDbFactory(new MongoClient(dbInfo.getDbUrl(), Integer.parseInt(dbInfo.getRemark())), dbInfo.getDbDriver());
        }
        return new SimpleMongoDbFactory(new MongoClient(host, port), database);
    }

    public MongoDbFactory mongoDbFactory1(){
        Map<String, String> map = new HashMap<>();
        map.put("dbType", "3");//mongodb
        map.put("belong", DbinfoBelongEnum.SHARED_MONGODB.getKey());
        List<DbInfo> dbInfos = dbInfoMapper.query(map);
        System.out.println(JSON.toJSONString(dbInfos));
        if(ListUtils.isNotEmpty(dbInfos)) {
            DbInfo dbInfo = dbInfos.get(0);
            ServerAddress serverAddress = new ServerAddress(dbInfo.getDbUrl(), Integer.parseInt(dbInfo.getRemark()));
            List<MongoCredential> credentialsList = new ArrayList<>();
            credentialsList.add(MongoCredential.createCredential(dbInfo.getDbUserName(), dbInfo.getDbDriver(), dbInfo.getDbPassword().toCharArray()));
            return new SimpleMongoDbFactory(new MongoClient(serverAddress, credentialsList), dbInfo.getDbDriver());
        }
        ServerAddress serverAddress = new ServerAddress(host, port);
        List<MongoCredential> credentialsList = new ArrayList<>();
        credentialsList.add(MongoCredential.createCredential(username, database, password.toCharArray()));
        return new SimpleMongoDbFactory(new MongoClient(serverAddress, credentialsList),database);
    }

    @Bean(name="sharedMongoTemplate")
    @Primary
    public MongoTemplate getMongoTemplate() {

        return new MongoTemplate(mongoDbFactory());
    }

    public static void main(String[] args) {
        //MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(new MongoClient("10.41.1.194", 27017), "gateway");
        //MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory);
        //Query query = new Query(Criteria.where("status").is(200));
        //Long count = mongoTemplate.count(query, "service_log");
        //System.out.println(count);

        /*Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("application_id").ne("-").and("status").is(200)),
                Aggregation.group("application_id").count().as("sum")
        );
        AggregationResults<BasicDBObject> aggregationResults =
                mongoTemplate.aggregate(aggregation, "service_log", BasicDBObject.class);
        List<DBObject> list = new ArrayList<>();
        for (Iterator<BasicDBObject> iterator = aggregationResults.iterator(); iterator.hasNext(); ) {
            DBObject obj = iterator.next();
            list.add(obj);
            //System.out.println("测试collection_rank_mongodb：" + obj.get("sum").toString());
        }

        Collections.sort(list, new Comparator<DBObject>() {
            @Override
            public int compare(DBObject o1, DBObject o2) {
                int sum1 = (int)o1.get("sum");
                int sum2 = (int)o2.get("sum");
                return (sum1 <= sum2 ? 1 : -1);
            }
        });
        System.out.println("测试collection_rank_mongodb：" + JSON.toJSONString(list));*/

    }
}
